using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.RecipeFramework;
using Microsoft.Practices.Common;
using System.IO;
using System.Xml;
using System.ComponentModel.Design;
using Microsoft.Practices.ComponentModel;
using EnvDTE;

namespace Microsoft.Practices.RepositoryFactory.ValueProviders
{
    [ServiceDependency(typeof(IDictionaryService)), ServiceDependency(typeof(DTE))]
    public class RecipeStateValueProvider : ValueProvider, IAttributesConfigurable
    {
        private string solutionPath;
        private string solutionName;

        public override bool OnBeginRecipe(object currentValue, out object newValue)
        {
            newValue = GetValue();
            return true;
        }

        private object GetValue()
        {
            IDictionaryService service = (IDictionaryService) ServiceHelper.GetService(this, typeof(IDictionaryService));
            solutionName = service.GetValue("SolutionNameArgument").ToString();
            solutionPath = service.GetValue("SolutionPathArgument").ToString();

            string fileName = string.Format(@"{0}\{1}.rcpstate", solutionPath, solutionName);
            
            XmlDocument document = new XmlDocument();
            if (!File.Exists(fileName))
            {    
                XmlNode rootNode = document.CreateElement("repositoryInformation");
                document.AppendChild(rootNode);
                document.Save(fileName);
                return document;
            }
            
            document.Load(fileName);

            return document;
        }

        public void Configure(System.Collections.Specialized.StringDictionary attributes)
        {
            if (attributes == null)
                throw new ArgumentNullException("attributes");

            solutionName = attributes["SolutionNameArgument"];
            solutionPath = attributes["SolutionPathArgument"];
        }
    }
}
